package uk.co.cocking.getinline2.testhelpers;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

public class FileTesting {
	

    public static void delete(File... files) {
	      for (File file: files) {
	         FileUtils.deleteQuietly(file);
	      }
	      
	   }
	
	public static Matcher<File> exists() {
	      return new TypeSafeMatcher<File>() {
	          File fileTested;

	          public boolean matchesSafely(File item) {
	              fileTested = item;
	              return item.exists();
	          }

	          public void describeTo(Description description) {
	              description.appendText(" that file ");
	              description.appendValue(fileTested);
	              description.appendText(" exists");
	          }
	      };
	  }

	   public static Matcher<File> contains(final String...expectedStrings) {
	      return new TypeSafeMatcher<File>() {
	         File fileTested;
	         
	         public boolean matchesSafely(File item) {
	            fileTested = item;
	            String contents;
	            try {
	               contents = FileUtils.readFileToString(item);
	            } catch (IOException e) {
	               return false;
	            }
	            for (String expectedString: expectedStrings) {
	               if (!contents.contains(expectedString)) {
	                  return false;
	               }
	            }
	            return true;
	         }
	         
	         public void describeTo(Description description) {
	            description.appendText(" that file ");
	            description.appendValue(fileTested);
	            description.appendText(" contains ");
	            description.appendText(StringUtils.join(expectedStrings, ", "));
	         }
	      };
	   }
	   public static Matcher<File> doesNotContain(final String...unwantedStrings) {
	      return new TypeSafeMatcher<File>() {
	         File fileTested;
	         
	         public boolean matchesSafely(File item) {
	            fileTested = item;
	            String contents;
	            try {
	               contents = FileUtils.readFileToString(item);
	            } catch (IOException e) {
	               return false;
	            }
	            for (String string: unwantedStrings) {
	               if (contents.contains(string)) {
	                  return false;
	               }
	            }
	            return true;
	         }
	         
	         public void describeTo(Description description) {
	            description.appendText(" that file ");
	            description.appendValue(fileTested);
	            description.appendText(" does not contain ");
	            description.appendText(StringUtils.join(unwantedStrings, ", "));
	         }
	      };
	   }

}
